import os,io
from flask import  render_template, request, redirect, url_for,session,Response,jsonify
import base64
from aip import AipFace
from aip import AipImageClassify
import cv2
import numpy as np
import hashlib
import pet_sqlite_methods as psm
from pet_sqlite_methods import User,Userre,Petmsg,Pclasstable
import pet_others
import spider_msg
import base64  
import time
app=psm.app
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = os.urandom(32)
PEOPLE_FOLDER = os.path.join('./static', 'images/')#获取图片路径
app.config['UPLOAD_FOLDER'] = PEOPLE_FOLDER#设置上传的图片保存路径
ALLOWED_EXTENSIONS = set(['.png','.jpg','.jpeg','.gif'])
# name=session['user']
from uuid import uuid4
import pet_others
@app.route("/ai",methods=["POST"])
def ai():
    # 1.保存录音文件
    audio = request.files.get("record")
    filename = f"{uuid4()}.wav"
    audio.save(filename)
    #2.将录音文件转换为PCM发送给百度进行语音识别
    q_text = pet_others.audio2text(filename)
    import os
    #删除录音文件
    os.remove(filename+'.pcm')
    os.remove(filename)
    return jsonify({"filename":q_text})    

@app.route('/',methods=['POST','GET'])
def index():
    try:
        name=session['user']
    except:
        name=None
    listid=psm.querypetid()
    if len(listid) <= 30:
        lenid = len(listid)
        return render_template('index.html',name=name,listid=listid,lenid=lenid)
    else:
        listid=listid[:31]
        lenid = len(listid)
        return render_template('index.html',name=name,listid=listid,lenid=lenid)
    
@app.route("/userlogout",methods=['GET','POST'])
def userlogout():
    #session.clear()
    try:
       session['user']=None
    except:
       session.clear() 
    return render_template('login/userlogin.html') 
  
@app.route('/login',methods=['POST','GET'])
def loginpage():
    page = request.values.get('page',"index")
    getmsg = request.args.get('msg')
    if request.method == 'GET':
        flag =request.values.get('flag','0')
        return render_template("login/userlogin.html",flag=flag,page=page)
    elif request.method == 'POST':
        uname =request.form['uname']
        password = request.form['password']
        password = hashlib.md5(password.encode()).hexdigest() 
        user =psm.loginguery(uname,password)
        #print('看看会话v',session['verifycode'])
        flagvc =True
        #获取验证码框里面的内容
        vc = request.form['verifycode']
        #判断验证码是否正确
        if vc  != session['verifycode']:
            flagvc =False
        else:
            flagvc
        if user != None and flagvc == True:
             session["user"] = user.uname
             #登录成功
             name = session["user"]
             #print(id(session))
             #print(flagvc)
             #return render_template('index.html',page=page,name=name)
             return redirect(url_for('index',name=name,page=page))
        else:#登录失败
            if flagvc==False:
                return render_template('login/userlogin.html',msg = "验证码不正确",page=page)
            else:
                #print(user)
                return render_template('login/userlogin.html',msg = "用户名或密码错误",page=page)    
    return render_template('login/userlogin.html',msg = getmsg)
        
@app.route("/userfacelogin",methods=['GET','POST'])
def userfacelogin():
    # path = "static/imgs/userpics/admin.png"
    # adminimgstr = base64.b64encode(open(path,"rb").read() ).decode()
    #页面摄像头捕捉到的人脸
    pageimgstr = request.form['imgstr']
    cascade_path = "haarcascade_frontalface_alt.xml"
    #检测有没有人脸出现
    faceCascade = cv2.CascadeClassifier(cascade_path) #可看作是人脸检测器
    predict_image = base64.b64decode(pageimgstr)
    predict_image = np.frombuffer(predict_image,np.uint8)
    predict_image = cv2.imdecode(predict_image,0)
    faces = faceCascade.detectMultiScale(predict_image,1.1,2,minSize=(100,100))
    #print(faces)
    if len(faces) == 0:
        return ""
    API_ID = "33606351"
    API_KEY="C63gjVeLLR5MLWWcsWXZG1pV"
    SECRET_KEY ="RULjZEBO64gm1v4jKl8TeAxo9MIISw0I"

    client = AipFace(API_ID,API_KEY,SECRET_KEY)
    ulist = psm.queryallusers()
    for u in ulist:
        #print(psm.getface(u.uid))
        try:
            result = client.match([
            {"image":psm.getface(u.uid),"image_type":"BASE64"},
            {"image":pageimgstr,"image_type":"BASE64"}
            ])
            if result['result']['score'] >= 82:
                session['user'] = u.uname
                return "登录成功"
        except:
             pass
    return "登陆失败，可能没有头像注册，请换其他方式登陆"
    # if(result['error_code'] == 0 and result['result'] != None and result['result']['score'] >=90):
    #     session['user'] = path[path.rfind("/")+1:len(path)-4]
    #     return "登录成功"
    # else:
    #     return "登陆失败，可能没有头像注册，请换其他方式登陆"
    
@app.route('/register',methods=['POST','GET'])
def registerpage():
    if request.method == 'POST':
        #获取验证码框里面的内容
        vc = request.form['verifycode']
        uname =request.form['uname']
        password = request.form['password']
        comparelist=psm.queryunamelist(uname)
        #print(vc)
        #非空验证
        if uname == '' or password == '':
            # print(type(uname))
            return render_template('login/register.html',msg ="用户名或密码不能为空")
        #判断用户名是否重复
        elif comparelist != []:
             return render_template('login/register.html',msg ="不好意思,该用户名已存在,请重新输入用户名")
        elif vc != session['verifycode']:
            return render_template('login/register.html',msg ="验证码输入错误!请重新输入")
        else:
            password = hashlib.md5(password.encode()).hexdigest() 
            usermsg = Userre(uname=uname,password=password)
            addres=psm.adduser(usermsg)
            return redirect(url_for('loginpage',msg=addres))
    #这个返回页面模板得写,要不然url地址找不到页面模板
    return render_template('login/register.html')

#生成验证码
@app.route('/verifycode/',methods=['POST','GET'])
def verifycode():
    if request.method == 'GET':
        buf=pet_others.verifycode(session)
        #这里要指定图片格式，注意buf.getvalue()是bytes字节类型
        return Response(buf.getvalue(), mimetype='image/png')
       

#宠物图片网址以及放置地
@app.route('/displayimg<int:pid>')
def display(pid):
    try:
        # plist = psm.petmsg_query()
        plist = psm.pet_img_query(pid)
        # recieve = plist[pid-1].pet_img
        #print('查看信息',plist)
        recieve = plist[0].pet_img
        bytes_rec=base64.b64decode(recieve)
        return Response(bytes_rec,mimetype='image/png')
    except:
        return "数字范围超出网站所给的设定"
#信息查询
# @app.route('/querymsg')        
# def querymsg():
#     msglist=psm.petmsg_query()
    
#     return render_template('querymsg.html',msglist=msglist)
@app.route("/querypagemsg",methods=['GET','POST'])
def bpagequery(*msg):
    try:
        name =session['user']
    except:
        name=None
    pname = request.values.get("pname","")
    address =request.values.get('address','')     
    ability =request.values.get('ability','')
    pclass = request.values.get("pclass","")
   
    currpage = int(request.values.get("currpage",1)) #当前页
    pclasslist = psm.queryallpclass()
    recieve = request.values.get("msg1","") #获取按钮点击
    if recieve == '点击了':
        currpage =1
        page = psm.querypage(pname,address,ability,pclass,currpage)
        if len(msg) == 0:
            pd = {"page":page}
        else:
            pd = {"page":page,"msg":msg}
        return render_template("querymsg.html",pd=pd,pclasslist=pclasslist,name=name)
    else:
        page = psm.querypage(pname,address,ability,pclass,currpage)
        if len(msg) == 0:
            pd = {"page":page}
        else:
            pd = {"page":page,"msg":msg}
        return render_template("querymsg.html",pd=pd,pclasslist=pclasslist,name=name)
#宠物图片识别  
lists=[]
@app.route('/identify',methods=['GET','POST'])
def identify():
    try:
        name =session['user']
    except:
        name=None
    if name == None:
       return render_template('login/userlogin.html',msg='请先登录')
    if request.method == 'POST':
       #获取上传框的文件
       file = request.files.get('input')
       if (file.filename == ''):
          lists.clear()
          return render_template("identify.html",name=name)
       else:
          #print('文件名',file.filename)
          file_path = app.config['UPLOAD_FOLDER']
          #保存文件
          totalfileurl= file_path+'/test/' + file.filename
          file.save(totalfileurl)
          full_filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
          APP_ID = '41727368'
          API_KEY = 'b6gf1mlQXvs81kifVtQQF5V8'
          SECRET_KEY = 'UoMX3sxDX5Su85zNbQY1EpiXk4RDwN9q'
          client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)
          fp = open(totalfileurl, 'rb')
          image = fp.read()
          result = client.animalDetect(image)#图片识别的结果
          print('识别结果',result)
          #core_name = ''
          try:
            if result['result'] != None and len(result['result'])>=1:
                    get1 = result['result'][0]['name']
                    get2 = result['result'][1]['name']
                    get3 = result['result'][2]['name']
                    get4 = result['result'][3]['name']
                    pet_name1=get1.strip(get1[-1])
                    pet_name2=get2.strip(get2[-1])
                    pet_name3=get3.strip(get3[-1])
                    pet_name4=get4.strip(get4[-1])
                    plist=[]
                    plist1 = psm.querypname(pet_name1)
                    if plist1 != []:
                       plist.append(plist1)

                    plist2 = psm.querypname(pet_name2)
                    if plist2 != []:
                       plist.append(plist2)

                    plist3 = psm.querypname(pet_name3)
                    if plist3 != []:
                       plist.append(plist3)

                    plist4 = psm.querypname(pet_name4)
                    if plist4 != []:
                       plist.append(plist4)
                    print(plist)
                    return render_template('identify.html',plist=plist,name=name)
          except:
              return render_template('identify.html',notanimal='非动物',name=name)
                
            #data = list(select_by_id(id))
            # querys = select_by_name("%"+core_name+"%")#这是一个根据苹果查询病害，但还没有真正实现
            # data = []
            # if len(querys)>=1:
            #     data = list(querys[0])
            # else:
            #     data = ['','','','','','']
            # data.append(full_filename)
            # lists.insert(0, data)
            #print(data)
    else:
        return render_template('identify.html',name=name)
#用户中心    
@app.route('/userCenter',methods=['POST','GET'])
def userCenter(*msg):
    msg = request.args.get('msg','0')
    try:
        name =session['user']
    except:
        name=None
    data=[]
    msglist = psm.queryusermsg(name)
    clist=psm.queryselfcontext(name) #说说个人信息表
    for i in msglist:
        data.append(i.uname)
        data.append(i.liveaddress)
        data.append(i.address)
        data.append(i.career)
        data.append(i.tel)
        data.append(i.usermsg)
    return render_template('users/userCenter.html',name=name,data=data,msg=msg,clist=clist)

#修改用户信息
@app.route('/updateusermsg',methods=['GET','POST'])
def updateusermsg():
    getname=request.form['getname']
    uname=request.form['uname']
    address=request.form['address']
    liveaddress=request.form['liveaddress']
    career = request.form['career']
    tel = request.form['tel']
    usermsg = request.form['usermsg']
    password = request.form['upassword']
    
    #记得会话里面的用户名也要改
    try:
       session['user']=uname
    except:
        pass
    
    msg = psm.updateuser(getname=getname,uname=uname,address=address,liveaddress=liveaddress,career=career,tel=tel,
          usermsg=usermsg,password=password)
    return redirect(url_for('userCenter',msg=msg))
   
        

#用户图像网址
@app.route('/showprofileimg=<string:uname>',methods=['POST','GET'])
def showprofileimg(uname):
    name=session.get('user','')
    # if name == '':
    #     name =None
    try:
        if name != None:
            imglist=psm.queryprofileimg(uname)
            img = imglist[0].profileimg
            #print(img)
            bytes_img = base64.b64decode(img)
            return Response(bytes_img,mimetype='image/png')
        else:
             return "您没有权限查看用户图片"
    except:
        return "您没有权限查看用户图片"
    
#改变用户图像
@app.route('/changuserimg/<string:uname>',methods=['GET','POST'])
def changeuserimg(uname):
    name=session.get('user','')
    imgfile = request.files["userimg"]
    nowtime2 = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))
    filename=imgfile.filename
    uploadpath=PEOPLE_FOLDER
    if filename != '':
        filename = nowtime2+".png"
        imgfile.save(uploadpath+filename)
        with open(uploadpath+filename, 'rb') as f:  
             image_data = f.read()  
        image_data_base64 =  base64.b64encode(image_data).decode('utf-8')     
        res = psm.updateuserimg(getname=uname,changeimg=image_data_base64)
        return userCenter(res) 
    return redirect(url_for('userCenter'))
       

 #新加说说方法1
@app.route('/addcontext',methods=['POST','GET']) 
def addcontext():
    uname=request.form['uname']
    context=request.form['context']
    #设置日期给文件名的准备
    nowtime2 = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))
        #获取图片对象
    f = request.files["attachment"]
        #获取上传文件的路径
    uploadpath = PEOPLE_FOLDER
    filename=f.filename
    # ree = filename is ''
    # print(ree)
    if filename != '' and filename != None:
        filename = nowtime2+".png"
            #print(filename)
            #保存文件
        f.save(uploadpath +"context/"+ filename)
        msg = psm.addcontext(uname,context=context,conimg=filename)
        return redirect(url_for('userCenter',msg=msg))
    else:
        msg = psm.addcontext(uname,context=context,conimg=None)
        return redirect(url_for('userCenter',msg=msg))
  
#删除说说
@app.route("/delcontext/<int:cid>/<string:conimg>",methods=['POST','GET'])    
def delcontext(cid,conimg):
    name=session.get('user','')
    msg = psm.delcontext(cid)
    try:
       os.remove('static\images\context\%s'%conimg)
    except:
        pass
    return redirect(url_for('userCenter',msg=msg))

#编辑说说
@app.route("/editcontext",methods=['POST','GET'])    
def editcontext():
    name=session.get('user','')
    uploadpath = PEOPLE_FOLDER
    context = request.form['edit_context']
    getid=request.form['conid']
    filestr=f'alterfile{getid}'
    #时间准备
    nowtime2 = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))
    imgfile = request.files[filestr]
    # print(imgfile.read())
    imgname =imgfile.filename
    if imgname != '' and imgname != None:
        filename = nowtime2+".png"
        imgfile.save(uploadpath +"context/"+ filename)
        
        msg = psm.editcontext(getid=getid,context=context,filename=filename)
        return redirect(url_for('userCenter',msg=msg))
    else:
        msg = psm.editcontext(getid=getid,context=context,filename = None)
        return redirect(url_for('userCenter',msg=msg))
#增加评论方法-个人中心
@app.route('/addcommentcenter',methods=['POST','GET'])
def addcommentcenter():
    name=session.get('user','')
    cid = request.form['commet_cid']  
    commentname = request.form['commentname']
    comment = request.form['comment']
    psm.addcomment(cid=cid,comment=comment,commitname=commentname)
    return redirect(url_for('userCenter',name=name)) 
#删除评论方法-个人中心
@app.route('/delcommentcenter/<int:id>',methods=['POST','GET'])
def delcommentidcenter(id):
    name=session.get('user','')
    psm.delcomment(id)
    return redirect('/userCenter?name=%s'%name)
#圈友交流      
@app.route('/user_com',methods=['POST','GET'])
def user_com(*msg):
    try:
        name=session['user']
    except:
        name=None
    if name == None:
        return render_template('login/userlogin.html',msg='请先登录')
    else:
        msg = request.args.get('msg','0')
            #print(msg)
        clist = psm.querycontext()
        return render_template('users/user_com.html',name=name,clist=clist,msg=msg)   
    
#删除朋友圈说说
@app.route("/delcontextc/<int:cid>/<string:conimg>",methods=['POST','GET'])    
def delcontextc(cid,conimg):
    name = session.get('user','')
    res = psm.delcontext(cid)
    msg = res
    try:
       os.remove('static\images\context\%s'%conimg)
    except:
        pass
    #return redirect('/user_com?name=%s'%name,msgdic=msgdic)
    return redirect(url_for('user_com',msg=msg,name=name))
#新加朋友圈说说
@app.route('/addcontextc',methods=['POST','GET']) 
def addcontextc():
    uname=request.form['uname']
    context=request.form['context']
    print(context)
    #设置日期给文件名的准备
    nowtime2 = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))
        #获取图片对象
    f = request.files["attachment"]
        #获取上传文件的路径
    uploadpath = PEOPLE_FOLDER
    filename=f.filename
    if filename != '' and filename != None:
        filename = nowtime2+".png"
        f.save(uploadpath +"context/"+ filename)
        msg = psm.addcontext(uname,context=context,conimg=filename)
        return redirect(url_for('user_com',msg=msg))
    else:
        msg = psm.addcontext(uname,context=context,conimg=None)
        return redirect(url_for('user_com',msg=msg))
#修改朋友圈说说
@app.route("/editcontextc",methods=['POST','GET'])    
def editcontextc():
    uploadpath = PEOPLE_FOLDER
    context = request.form['edit_context']
    getid=request.form['conid']
    filestr=f'alterfile{getid}'
    #时间准备
    nowtime2 = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))
    imgfile = request.files[filestr]
    imgname =imgfile.filename
    if imgname != '' and imgname != None:
        filename = nowtime2+".png"
        imgfile.save(uploadpath +"context/"+ filename)
        
        msg = psm.editcontext(getid=getid,context=context,filename=filename)
        return redirect(url_for('user_com',msg=msg))
    else:
        msg = psm.editcontext(getid=getid,context=context,filename = None)
        return redirect(url_for('user_com',msg=msg))
#增加评论方法
@app.route('/addcomment',methods=['POST','GET'])
def addcomment():
    name=session.get('user','')
    cid = request.form['commet_cid']  
    commentname = request.form['commentname']
    comment = request.form['comment']
    psm.addcomment(cid=cid,comment=comment,commitname=commentname)
    return redirect(url_for('user_com',name=name))

#删除评论方法
@app.route('/delcomment/<int:id>',methods=['POST','GET'])
def delcommentid(id):
    name=session.get('user','')
    psm.delcomment(id)
    return redirect('/user_com?name=%s'%name)

#后台管理-宠物信息管理
@app.route('/admin_pet',methods=['POST','GET'])
def admin_pet(*msg,flagpage=0):
    name = session.get('user','')
    print(name)
    if name  == '':
        return render_template('login/userlogin.html',msg='请先登录')
    elif name != 'admin':
        return render_template('login/userlogin.html',msg='请用管理员账号登录')
    pname = request.values.get("pname","")
    address =request.values.get('address','')
    ability =request.values.get('ability','')
    pclass = request.values.get("pclass","")
    currpage = int(request.values.get("currpage",1)) #当前页
    pclasslist = psm.queryallpclass()
    recieve = request.values.get("msg1","") #获取按钮点击
    current_page = int(request.args.get('current_page','0'))
    if recieve == '点击了':
        currpage =1
        page = psm.admin_querypage(pname,address,ability,pclass,currpage)
        if len(msg) == 0:
            pd = {"page":page}
        else:
            pd = {"page":page,"msg":msg}
        return render_template('admin/admin_pet.html',pd=pd,pclasslist=pclasslist,name=name)
    elif flagpage != 0:
        page = psm.admin_querypage(pname,address,ability,pclass,currpage=flagpage)
        if len(msg) == 0:
            pd = {"page":page}
        else:
            pd = {"page":page,"msg":msg}
        return render_template("admin/admin_pet.html",pd=pd,pclasslist=pclasslist,name=name) 
    elif current_page != 0: #删除后依然在当前页
        page = psm.admin_querypage(pname,address,ability,pclass,currpage=current_page)
        if len(msg) == 0:
            pd = {"page":page}
        else:
            pd = {"page":page,"msg":msg}
        return render_template("admin/admin_pet.html",pd=pd,pclasslist=pclasslist,name=name) 
    else:
        page = psm.admin_querypage(pname,address,ability,pclass,currpage)
        if len(msg) == 0:
            pd = {"page":page}
        else:
            pd = {"page":page,"msg":msg}
        return render_template("admin/admin_pet.html",pd=pd,pclasslist=pclasslist,name=name)
    
#宠物信息添加
@app.route('/addpetmsg',methods=['POST','GET'])
def addpetmsg():
    pname,oname,address =request.form['pnameadd'], request.form['onameadd'],request.form['addressadd']    
    ability,pmsg,pet_his= request.form['abilityadd'],request.form['petmsgadd'],request.form['pet_hisadd']       
    pet_fit =request.form['pet_fitadd']
    bueaty,pet_clingy= request.form['bueatyadd'],request.form['pet_clingyadd']
    pet_kind,pet_smart, pet_honest  = request.form['pet_kindadd'],request.form['pet_smartadd'],request.form['pet_honestadd']
    pclass = request.form['pclassadd']
    petimg = request.files['petimg']
    byte_img = petimg.read()
    img_base64 = base64.b64encode(byte_img).decode('utf-8')  
    byte_img = bytes(img_base64,encoding='utf-8')
    pmsglist = Petmsg(pname=pname,oname=oname,address=address,ability=ability,pmsg=pmsg,pet_his=pet_his,pet_fit=pet_fit,bueaty=bueaty,
    pet_clingy=pet_clingy,pet_kind=pet_kind,pet_smart=pet_smart,pet_honest=pet_honest,pclass=pclass,pet_img=byte_img)
    res = psm.pet_add(pmsglist)
    lastpage = int(request.form['lastpage'])
    currentpage =int(request.form['currentpage'])
    if res == '宠物信息添加成功!':
       return admin_pet(res,flagpage=lastpage)
    else:
       return admin_pet(res,flagpage=currentpage)

#宠物信息删除
@app.route('/pdel/<int:pid>/<int:current_page>',methods=['POST','GET'])
def pdel(pid,current_page):
    res = psm.pet_del(pid)
    return redirect(url_for('admin_pet',res=res,current_page=current_page))

#宠物信息编辑
@app.route('/updatepet',methods=['POST','GET'])
def updatepet():
    pname,oname,address = request.form['pnameu'],request.form['onameu'],request.form['addressu']    
    ability,pmsg,pet_his= request.form['abilityu'],request.form['petmsgu'],request.form['pet_hisu']       
    pet_fit =request.form['pet_fitu']
    bueaty,pet_clingy= request.form['bueatyu'],request.form['pet_clingyu']
    pet_kind,pet_smart, pet_honest  = request.form['pet_kindu'],request.form['pet_smartu'],request.form['pet_honestu']
    try:
       pclass = request.form['pclassu']
    except:
       pclass=''
    getid = request.form['pidu']
    petimg = request.files['petimgu']
    byte_img = petimg.read()
    current_page = int(request.form['current_page'])
    #print(byte_img)
    if byte_img == b'':
        res=psm.pet_update(getid=getid,pname=pname,oname=oname,address=address,ability=ability,pmsg=pmsg,pet_his=pet_his,pet_fit=pet_fit,bueaty=bueaty,
        pet_clingy=pet_clingy,pet_kind=pet_kind,pet_smart=pet_smart,pet_honest=pet_honest,pclass=pclass,pet_img=byte_img)
        return admin_pet(res,flagpage=current_page)
    else:
        img_base64 = base64.b64encode(byte_img).decode('utf-8')  
        byte_img = bytes(img_base64,encoding='utf-8')
        res=psm.pet_update(getid=getid,pname=pname,oname=oname,address=address,ability=ability,pmsg=pmsg,pet_his=pet_his,pet_fit=pet_fit,bueaty=bueaty,
        pet_clingy=pet_clingy,pet_kind=pet_kind,pet_smart=pet_smart,pet_honest=pet_honest,pclass=pclass,pet_img=byte_img)
        return admin_pet(res,flagpage=current_page)
    
#后台管理-宠物信息类别管理
@app.route('/admin_pclass',methods=['POST','GET'])
def admin_pclass(*msg,flagpage=0):
    name = session.get('user','')
    if name  == '':
        return render_template('login/userlogin.html',msg='请先登录')
    elif name != 'admin':
        return render_template('login/userlogin.html',msg='请用管理员账号登录')
    cname =request.values.get('pclass','')
    currpage = int(request.values.get("currpage",1)) #当前页
    recieve = request.values.get("msg1","") #获取按钮点击
    current_page = int(request.args.get('currentpage','0'))
    if recieve == '点击了':
       currpage =1
       page = psm.querypagepclass(cname=cname,currpage=currpage)
       if len(msg) == 0:
            pdc = {"page":page}
       else:
            pdc = {"page":page,"msg":msg}
       return render_template('admin/admin_petclass.html',pdc=pdc,name=name)
    elif flagpage != 0:
       page = psm.querypagepclass(cname=cname,currpage=flagpage)
       if len(msg) == 0:
            pdc = {"page":page}
       else:
            pdc = {"page":page,"msg":msg}
       return render_template('admin/admin_petclass.html',pdc=pdc,name=name)
    elif current_page != 0: #删除后依然在当前页
        page = psm.querypagepclass(cname=cname,currpage=current_page)
        if len(msg) == 0:
            pdc = {"page":page}
        else:
            pdc = {"page":page,"msg":msg}
        return render_template('admin/admin_petclass.html',pdc=pdc,name=name)
    else:
        page = psm.querypagepclass(cname=cname,currpage=currpage)
        if len(msg) == 0:
            pdc = {"page":page}
        else:
            pdc = {"page":page,"msg":msg}
        return render_template("admin/admin_petclass.html",pdc=pdc,name=name)
    
#添加宠物类别信息   
@app.route('/addpclass',methods=['POST','GET'])   
def addpclass():
     classname= request.form['classname']
     lastpage =int(request.form['lastpage'])
     current_page =int(request.form['current_page'])
     pclasslist = Pclasstable(fk=classname,pclass=classname)
     res = psm.addclass(pclasslist=pclasslist)
     if res == '宠物类别信息添加成功!':
        return admin_pclass(res,flagpage=lastpage)
     else:
        return admin_pclass(res,flagpage=current_page)
     

#修改宠物类别信息    
@app.route('/updatepclass',methods=['POST','GET'])
def updatepclass():
    getid = request.form['pclassidu']
    pclass = request.form['pclassu']
    currentpage = int(request.form['currentpage'])
    res = psm.updateclass(getid=getid,classname=pclass)
    return admin_pclass(res,flagpage=currentpage)

#删除宠物类别信息
@app.route('/pclassdel/<int:id>/<int:currentpage>',methods=['POST','GET'])
def pclassdel(id,currentpage):
    res = psm.delclass(id)
    return redirect(url_for('admin_pclass',res=res,currentpage=currentpage))

#爬取宠物数据
@app.route('/catch_spyder',methods=['POST','GET'])
def catch_spyder():
    listid =[]
    lastpage =int(request.form['lastpage'])
    numberselector = int(request.form['dropdown_spyder'])#获取输入框数目
    for n in range(numberselector):
        
        name = 'select_input'+str(n+1)
        n = request.form[name]
        listid.append(n)
    successcout,failcount = spider_msg.spyder_main(listid)
    res = '爬取成功了%d次,爬取失败了%d次'%(successcout,failcount)  
    print(res) 
    return admin_pet(res,flagpage=lastpage)

#后台管理-用户信息管理
@app.route('/admin_user',methods=['POST','GET'])
def admin_user(*msg,flagpage=0):
    name = session.get('user','')
    if name  == '':
        return render_template('login/userlogin.html',msg='请先登录')
    elif name != 'admin':
        return render_template('login/userlogin.html',msg='请用管理员账号登录')
    uname =request.values.get('uname','')
    liveaddress =request.values.get('liveaddress','')
    career =request.values.get('career','')
    address =request.values.get('address','')
    tel = request.values.get('tel','')
    currpage = int(request.values.get("currpage",1)) #当前页
    current_page = int(request.args.get('currentpage','0'))#url上的当前页
    recieve = request.values.get("msg1","") #获取按钮点击
    if recieve == '点击了':
       currpage =1
       page = psm.userpagequery(uname=uname,liveaddress=liveaddress,career=career,address=address,tel=tel,currpage=currpage)
       if len(msg) == 0:
            pd = {"page":page}
       else:
            pd = {"page":page,"msg":msg}
       return render_template('admin/admin_user.html',pd=pd,name=name)
    elif flagpage != 0:
       page = psm.userpagequery(uname=uname,liveaddress=liveaddress,career=career,address=address,tel=tel,currpage=flagpage)
       if len(msg) == 0:
            pd = {"page":page}
       else:
            pd = {"page":page,"msg":msg}
       return render_template('admin/admin_user.html',pd=pd,name=name)
    elif current_page != 0: #删除后依然在当前页
        page = psm.userpagequery(uname=uname,liveaddress=liveaddress,career=career,address=address,tel=tel,currpage=current_page)
        if len(msg) == 0:
            pd = {"page":page}
        else:
            pd = {"page":page,"msg":msg}
        return render_template("admin/admin_user.html",pd=pd,name=name) 
    else:
        page = psm.userpagequery(uname=uname,liveaddress=liveaddress,career=career,address=address,tel=tel,currpage=currpage)
        if len(msg) == 0:
            pd = {"page":page}
        else:
            pd = {"page":page,"msg":msg}
        return render_template('admin/admin_user.html',pd=pd,name=name)

#用户信息添加
@app.route('/add_umsg',methods=['POST','GET'])   
def add_umsg():
    uname,password,liveaddress = request.form['uname1'],request.form['password1'],request.form['liveaddress1']
    address,carrer,tel = request.form['address1'],request.form['career1'],request.form['tel1']
    usermsg = request.form['usermsg1']
    password = hashlib.md5(password.encode()).hexdigest() 
    lastpage = int(request.form['lastpage'])
    currentpage =int(request.form['currentpage'])
    userimg_bytes = request.files['userimg1'].read()
    userimg_base64 = base64.b64encode(userimg_bytes).decode('utf-8')
    userimg_bytes = bytes(userimg_base64,encoding='utf-8')
    umsg = User(uname=uname,password=password,liveaddress=liveaddress,address=address,career=carrer,tel=tel,usermsg=usermsg,profileimg=userimg_bytes)
    res = psm.add_usermsg(umsg)
    if res == '用户添加成功!':
       return admin_user(res,flagpage=lastpage)
    else:
       return admin_user(res,flagpage=currentpage)
    
#用户删除
@app.route('/udel/<int:uid>/<int:currentpage>',methods=['POST','GET'])  
def udel(uid,currentpage):
    res = psm.del_usermsg(uid)
    return redirect(url_for('admin_user',res=res,currentpage=currentpage))
#用户信息编辑
@app.route('/updateuser',methods=['POST','GET'])  
def updateuser():
    getid = request.form['uidu']
    uname,password,liveaddress = request.form['unameu'],request.form['passwordu'],request.form['liveaddressu']
    address,carrer,tel = request.form['addressu'],request.form['careeru'],request.form['telu']
    usermsg = request.form['usermsgu']
    password = hashlib.md5(password.encode()).hexdigest() 
    currentpage =int(request.form['current_page'])
    userimg_bytes = request.files['userimgu'].read()
    if userimg_bytes == b'':
       res = psm.update_user(getid=getid,uname=uname,password=password,liveaddress=liveaddress,address=address,career=carrer,tel=tel,
       usermsg=usermsg,profileimg=userimg_bytes)
       return admin_user(res,flagpage=currentpage)
    else:
       userimg_base64 = base64.b64encode(userimg_bytes).decode('utf-8')
       userimg_bytes = bytes(userimg_base64,encoding='utf-8')
       res=psm.update_user(getid=getid,uname=uname,password=password,liveaddress=liveaddress,address=address,career=carrer,tel=tel,
       usermsg=usermsg,profileimg=userimg_bytes)
       return admin_user(res,flagpage=currentpage)
    


#设置特定评论的查询方法
@app.template_filter('querysomec')
def querysomec(val):
    somelist = psm.querysomec(val)
    return somelist

#自定义过滤器
# @app.template_filter('lenidlist')
# def lenidlist(lista):
#     listid = psm.querypetid()
#     lenid = len(lista)
#     return lenid

#自定义模板过滤器
@app.template_filter('cut')
def cut(value):
    value = value.replace("你好",'我被改变了')
    return value

# 定义一个自定义模板过滤器，用于输出数组  
@app.template_filter('array_filter')  
def array_filter(value):  
    if not isinstance(value, list):  
        value = [value]  
    return ', '.join(map(str, value))



@app.route('/test',methods=['GET','POST'])
def test():
    list1=psm.querypetid()
    lenid = len(list1)
    #print(lenid)
    return render_template('test.html',list1=list1)
if __name__ == '__main__':
    app.run(port=5001,host='0.0.0.0')
    